import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * The SortFilter sorts the data received from the input port and writes it to
 * the output port. The data is buffered by the filter for sorting before its
 * finally written to the output pipe.
 * 
 * @author Team-10
 * 
 */
public class SortFilter extends FilterFramework2 {

	public SortFilter() {
		// one input port and one output port
		super(1, 1);
	}

	// Run method executed by the thread
	public void run() {

		// List to buffer the measurement objects
		List<Measurement> dataList = new ArrayList<Measurement>();
		while (true) {
			/*************************************************************
			 * Here we read a byte and write a byte
			 *************************************************************/

			try {
				// read the measurement and buffers it to the list
				Measurement measurement = new Measurement();
				// read measurement from input port 0
				measurement.readByteStream(this, 0);
				dataList.add(measurement);

			}
			// closes the input port when end of stream is reached
			catch (EndOfStreamException e) {
				CloseInputPorts(0);
				break;
			} // catch

		}
		// Sort the buffered list
		Collections.sort(dataList, new MeasurementComparator());
		// Write the sorted list to the output port
		for (Measurement measurement : dataList) {
			measurement.writeByteStream(this, 0);

		}
		// Closes the output ports
		CloseOutputPorts(0);

	}

}
